package com.tengju.bff.interfaces.covercharge.job;

import com.tengju.bff.interfaces.covercharge.constant.HeavyKeyEnum;
import com.tengju.bff.interfaces.covercharge.entity.po.CustPaidTrans;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceSelfCertificationWithdraw;
import com.tengju.bff.interfaces.covercharge.entity.vo.CashBackRes;
import com.tengju.bff.interfaces.covercharge.service.ICustPaidTransService;
import com.tengju.bff.interfaces.covercharge.service.ICustTaskQueueService;
import com.tengju.bff.interfaces.covercharge.service.IServiceSelfCertificationWithdrawService;
import com.tengju.bff.interfaces.covercharge.util.alarmUtil.MsgSendUtil;
import com.tengju.bff.interfaces.covercharge.util.redis.HeavyUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.List;

@Component
@Slf4j
//自认证打款结果
public class CheckOrderResultsJob {

    @Autowired
    private IServiceSelfCertificationWithdrawService withdrawService;


    @Autowired
    private ICustTaskQueueService iCustTaskQueueService;

    @Autowired
    private ICustPaidTransService iCustPaidTransService;

    /**
     * 最大重试次数
     */
    private Integer maxTries = 10;

    @XxlJob("checkOrderResultsJob")
    public ReturnT<String> execute(String s) throws ParseException {
        if(HeavyUtil.isRun(HeavyKeyEnum.WITHDRAWAL_QUERY_JOB_E.getCode())) {
            log.info("=checkOrderResultsJob=已经有正在运行的,跳过");
            return ReturnT.SUCCESS;
        } else {
            try {
                return this.exec();
            } catch (Exception e) {
                log.error("=checkOrderResultsJob=执行异常", e);
                return ReturnT.SUCCESS;
            } finally {
                HeavyUtil.runDone(HeavyKeyEnum.WITHDRAWAL_QUERY_JOB_E.getCode());
            }
        }
    }


    private ReturnT<String> exec()
    {
        log.info("=checkOrderResultsJob_l=开始执行");
        List<CustPaidTrans> custPaidTransList = iCustPaidTransService.getCheckList();
        if(!(custPaidTransList.size() > 0)) {
            log.info("=checkOrderResultsJob_l=执行结束,没有需要执行的记录");

            return ReturnT.SUCCESS;
        }
        for (CustPaidTrans custPaidTrans : custPaidTransList) {
            CashBackRes res = null;
            try {
                res = HeavyUtil.runWithLock(HeavyKeyEnum.WITHDRAWAL_QUERY.getCode() + custPaidTrans.getWithdrawId(), () -> {
                    return withdrawService.doWithdrawalResultsQuery(custPaidTrans);

                });
                if("".equals(res.getErrorMessage())) {

                    log.info("=batchWithdrawalJob=提现批量处理成功一条;提现id:{}", custPaidTrans.getWithdrawId());
                } else {
                    this.replay(custPaidTrans, res);
                }

            } catch (Exception e) {
                this.replay(custPaidTrans, res);
                log.error("=batchWithdrawalJob=定时任务处理后台线上提现报错日志", e);
            }


        }
        log.info("=checkOrderResultsJob_l=执行结束,执行数:{}", custPaidTransList.size());

        return ReturnT.SUCCESS;
    }

    /**
     * 重试
     * @param custPaidTrans
     * @param res
     */
    private void replay(CustPaidTrans custPaidTrans, CashBackRes res) {
        CustPaidTrans upCustPaidTrans = new CustPaidTrans();
        upCustPaidTrans.setId(custPaidTrans.getId());
        Integer queryNum = custPaidTrans.getQueryNum() + 1;
        if(queryNum >= this.maxTries) {
            ServiceSelfCertificationWithdraw withdraw = new ServiceSelfCertificationWithdraw();
            withdraw.setId(custPaidTrans.getWithdrawId());
            withdraw.setQueryRemark("代付系统出现未知异常, 请联系专员进行排查");
            withdrawService.updateById(withdraw);
            MsgSendUtil.sendLarkMsg("服务费查询提现结果重试次数超过10次请排查;错误信息:" +res.getErrorMessage() + ";reqSn:" + custPaidTrans.getReqSn());
        }
        upCustPaidTrans.setQueryNum(queryNum);
        iCustPaidTransService.updateById(upCustPaidTrans);
    }




}
